package com.ruoyi.common.filter;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.resource.OperatorUserSystem;
import com.ruoyi.common.core.resource.OperatorUserSystemHolder;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidParameterException;

/**
 * @Description: 操作用户体系标识 Filter
 * @Company: 北京卡拉卡尔股份技术有限公司
 * @Author: Darren Ho
 * @Date: 10/9/2020 18:20
 */
public class OperatorUserSystemFilter extends AbstractResourceFilter {

    private static final String OPERATOR_USER_SYSTEM_HEADER = "X-User-System-ID";

    public OperatorUserSystemFilter(String exclude) {
        super(exclude);
    }

    public OperatorUserSystemFilter() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        doFilterInternal((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);

    }

    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws
            ServletException,
            IOException {
        String path = httpServletRequest.getServletPath();

        try {
            OperatorUserSystem operatorUserSystem;
            if (!isInExcludes(path)) {
                operatorUserSystem = extractOperatorUserSystem(httpServletRequest);
            } else {
                operatorUserSystem = OperatorUserSystem.SYS_USER;
            }

            OperatorUserSystemHolder.set(operatorUserSystem);
            filterChain.doFilter(httpServletRequest, httpServletResponse);

        } catch (Exception e) {
            responseException(httpServletResponse, e);

        } finally {
            OperatorUserSystemHolder.clear();
        }

    }

    public static OperatorUserSystem extractOperatorUserSystem(HttpServletRequest httpServletRequest) {

        String name = httpServletRequest.getHeader(OPERATOR_USER_SYSTEM_HEADER);

        if (!StringUtils.hasText(name)) {
            throw new InvalidParameterException("Only non-null operator user system  is permitted");
        }

        return OperatorUserSystem.valueOf(name);
    }

    private void responseException(HttpServletResponse response, Exception e) throws IOException {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json");
        response.getWriter().write(AjaxResult.error(e.getMessage()).toString());
        response.getWriter().close();
    }
}
